/**
 * TaskMaster v1 - Tasks Store
 * AceFlow v3.0 - Implementation Phase
 */

import { defineStore } from 'pinia'
import axios from 'axios'
import { useAuthStore } from './auth'

export const useTasksStore = defineStore('tasks', {
  state: () => ({
    tasks: [],
    loading: false,
    error: null,
    currentView: 'list' // 'list' or 'kanban'
  }),

  getters: {
    getTasks: (state) => state.tasks,
    getPendingTasks: (state) => state.tasks.filter(task => task.status === 'pending'),
    getInProgressTasks: (state) => state.tasks.filter(task => task.status === 'in_progress'),
    getCompletedTasks: (state) => state.tasks.filter(task => task.status === 'completed'),
    isLoading: (state) => state.loading,
    getError: (state) => state.error,
    getCurrentView: (state) => state.currentView
  },

  actions: {
    async fetchTasks(status = null) {
      this.loading = true
      this.error = null

      try {
        const params = status ? { status } : {}
        const response = await axios.get('/api/tasks/', { params })

        this.tasks = response.data
        return { success: true, tasks: response.data }
      } catch (error) {
        // Handle 401 Unauthorized (token expired)
        if (error.response?.status === 401) {
          // Clear authentication state
          const authStore = useAuthStore()
          authStore.logout()
          this.error = '登录已过期，请重新登录'
          return { success: false, message: this.error, redirectToLogin: true }
        }

        this.error = error.response?.data?.detail || '获取任务失败'
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },

    async createTask(taskData) {
      this.loading = true
      this.error = null

      try {
        const response = await axios.post('/api/tasks/', taskData)

        if (response.data.success) {
          // Refresh tasks list
          await this.fetchTasks()
          return { success: true, message: response.data.message, taskId: response.data.task_id }
        } else {
          return { success: false, message: response.data.message }
        }
      } catch (error) {
        // Handle 401 Unauthorized (token expired)
        if (error.response?.status === 401) {
          const authStore = useAuthStore()
          authStore.logout()
          this.error = '登录已过期，请重新登录'
          return { success: false, message: this.error, redirectToLogin: true }
        }

        this.error = error.response?.data?.detail || '创建任务失败'
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },

    async updateTask(taskId, updateData) {
      this.loading = true
      this.error = null

      try {
        const response = await axios.put(`/api/tasks/${taskId}`, updateData)

        if (response.data.success) {
          // Update local task
          const index = this.tasks.findIndex(task => task.id === taskId)
          if (index !== -1) {
            this.tasks[index] = { ...this.tasks[index], ...updateData }
          }

          return { success: true, message: response.data.message }
        } else {
          return { success: false, message: response.data.message }
        }
      } catch (error) {
        // Handle 401 Unauthorized (token expired)
        if (error.response?.status === 401) {
          const authStore = useAuthStore()
          authStore.logout()
          this.error = '登录已过期，请重新登录'
          return { success: false, message: this.error, redirectToLogin: true }
        }

        this.error = error.response?.data?.detail || '更新任务失败'
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },

    async deleteTask(taskId) {
      this.loading = true
      this.error = null

      try {
        const response = await axios.delete(`/api/tasks/${taskId}`)

        if (response.data.success) {
          // Remove from local tasks
          this.tasks = this.tasks.filter(task => task.id !== taskId)
          return { success: true, message: response.data.message }
        } else {
          return { success: false, message: response.data.message }
        }
      } catch (error) {
        // Handle 401 Unauthorized (token expired)
        if (error.response?.status === 401) {
          const authStore = useAuthStore()
          authStore.logout()
          this.error = '登录已过期，请重新登录'
          return { success: false, message: this.error, redirectToLogin: true }
        }

        this.error = error.response?.data?.detail || '删除任务失败'
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },

    async getTaskById(taskId) {
      try {
        const response = await axios.get(`/api/tasks/${taskId}`)
        return { success: true, task: response.data }
      } catch (error) {
        // Handle 401 Unauthorized (token expired)
        if (error.response?.status === 401) {
          const authStore = useAuthStore()
          authStore.logout()
          this.error = '登录已过期，请重新登录'
          return { success: false, message: this.error, redirectToLogin: true }
        }

        this.error = error.response?.data?.detail || '获取任务失败'
        return { success: false, message: this.error }
      }
    },

    setCurrentView(view) {
      this.currentView = view
    },

    clearError() {
      this.error = null
    },

    // Helper methods for priority and status
    getPriorityText(priority) {
      const priorities = {
        1: '高',
        2: '中',
        3: '低'
      }
      return priorities[priority] || '未知'
    },

    getPriorityColor(priority) {
      const colors = {
        1: 'danger',
        2: 'warning',
        3: 'success'
      }
      return colors[priority] || 'info'
    },

    getStatusText(status) {
      const statuses = {
        'pending': '待办',
        'in_progress': '进行中',
        'completed': '已完成'
      }
      return statuses[status] || '未知'
    },

    getStatusColor(status) {
      const colors = {
        'pending': 'info',
        'in_progress': 'primary',
        'completed': 'success'
      }
      return colors[status] || 'info'
    }
  }
})
